import React, { useState } from "react";
import { Form, Input, Button, Card, message } from "antd";
import { loginApi, getUserInfoApi } from "@/apis/user";
import { useDispatch } from "react-redux";
import { setToken, setProfile } from "@/store/modules/userStore";
import router from "@/router";

const Login: React.FC = () => {
  const dispatch = useDispatch();
  const [loading, setLoading] = useState(false);

  const login = async (values: any) => {
    setLoading(true);
    try {
      const res: any = await loginApi(values);
      if (res.code === 0 && res.token) {
        // 1. 保存 token
        dispatch(setToken(res.token));
        // 2. 获取并保存用户信息
        const userInfoRes: any = await getUserInfoApi();
        if (userInfoRes.code === 0) {
          dispatch(setProfile(userInfoRes.data));
        }
        // 3. 跳转首页
        message.success(`登录成功，欢迎：${values.username}`);
        router.navigate("/");
      } else {
        message.error(res.message || "登录失败");
      }
    } catch (error) {
      message.error("请求失败，请稍后再试");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div
      style={{
        minHeight: "100vh",
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        background: "#f0f2f5",
      }}
    >
      <Card title="后端管理系统" style={{ width: 350, textAlign: "center" }}>
        <Form
          name="login"
          initialValues={{ remember: true }}
          onFinish={login}
          autoComplete="off"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: "请输入用户名!" }]}
          >
            <Input placeholder="用户名" />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: "请输入密码!" }]}
          >
            <Input.Password placeholder="密码" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block loading={loading}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
